package cn.wowjoy.commonlibrary.utils;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;

import junit.framework.Assert;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片处理工具类
 */
public class ImageUtils {
    private static int calculateInSampleSize(BitmapFactory.Options options,
                                             int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响
    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth,
                                            int dstHeight) {
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) {
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res,
                                                         int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeResource(res, resId, options);
        return createScaleBitmap(src, reqWidth, reqHeight);
    }

    public static Bitmap decodeSampledBitmapFromFd(String pathName,
                                                   int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return src;
    }

    public static Bitmap getThumbBitmap(String fileName, float scale) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        float density = 160.0F * scale;
        options.inDensity = (int) density;
        Bitmap bitmap = BitmapFactory.decodeFile(fileName, options);
        if (bitmap != null) {
            return processBitmap(bitmap, /*bitmap.getWidth() / 15*/0);
        }

        return null;
    }

    /**
     * 生成一张缩略图
     *
     * @param bitmap
     * @param paramFloat
     * @return
     */
    public static Bitmap processBitmap(Bitmap bitmap, float paramFloat) {
        Assert.assertNotNull(bitmap);
        Bitmap resultBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        Paint paint = new Paint();
        Rect localRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(localRect);
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setFilterBitmap(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(-4144960);
        canvas.drawRoundRect(rectF, paramFloat, paramFloat, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, localRect, localRect, paint);
        bitmap.recycle();
        return resultBitmap;
    }

    private final static String Tag = ImageUtils.class.getSimpleName();


    public static Bitmap zoomImage(Bitmap bgimage, int maxHight, Context context) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        try {
            // 计算宽高缩放率
            float scaleWidth = ((float) ScreenUtils.getScreenWidth(context)) / width;
            if (maxHight < (int) (height * scaleWidth)) {
                scaleWidth = maxHight / height;
                Bitmap returnBitmap = Bitmap.createScaledBitmap(bgimage,
                        (int) (scaleWidth * width), maxHight, true);

                return returnBitmap;
            } else {
                Bitmap returnBitmap = Bitmap.createScaledBitmap(bgimage,
                        ScreenUtils.getScreenWidth(context),
                        (int) (height * scaleWidth), true);

                return returnBitmap;
            }
            // 缩放图片动作

        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            return bgimage;
        }
    }


    public static String encodeBase64File(File file) {
        try {
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return Base64.encodeToString(buffer, Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Bitmap base64toBitmap(String base64) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(base64, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public static String uri2path(Context ct, Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = ct.getContentResolver().query(uri, projection, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(projection[0]);
        String picturePath = cursor.getString(columnIndex);  //获取照片路径
        cursor.close();
        return picturePath;
    }

    public static File zoomImageFile(String imgPath, String outPath, int max) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);

        int realWidth = options.outWidth;
        int realHeight = options.outHeight;
        float scale = 1.0f;
        if (options.outWidth > options.outHeight) {
            if (options.outWidth > max)
                scale = max / (float) options.outWidth;
        } else {
            if (options.outHeight > max)
                scale = max / (float) options.outHeight;
        }
        options.inJustDecodeBounds = false;

        Bitmap rawBitmap = BitmapFactory.decodeFile(imgPath, options);
        Bitmap returnBitmap = Bitmap.createScaledBitmap(rawBitmap, (int) (realWidth * scale), (int) (realHeight * scale), true);

        File F = new File(outPath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(F));
            returnBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (rawBitmap != null)
            rawBitmap.recycle();
        if (returnBitmap != null)
            returnBitmap.recycle();
        return F;
    }
}